package com.haynes.meetxiaohai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.haynes.meetxiaohai.common.R;
import com.haynes.meetxiaohai.entity.User;
import com.haynes.meetxiaohai.service.UserService;
import com.haynes.meetxiaohai.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Haynes
 * @Date 2023/3/23 16:13
 * @PackageName:com.haynes.reggie.controller
 * @ClassName: UserController
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
//        获取手机号
        String phone = user.getPhone();
        if (phone != null) {
//        生成6位验证码并存入session
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("手机号验证码为:" + code);
//            存入session中
//            session.setAttribute(phone, code);
//            将验证码放置在缓存当中，并设置有效时为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

//          SMSUtils.sendMessage("遇见小海", "SMS_274530884", phone, code);


            R.success("短信发送成功!请注意查收");
        }
        return R.error("短信发送失败~");
    }

    @PostMapping("/login")
    public R<User> login(HttpSession session, @RequestBody Map<String, Object> map) {
//        获取手机号
        String phone = map.get("phone").toString();
//        获取验证码
        String code = map.get("code").toString();
//        获取sess当中的验证码
//        Object sessionIncode = session.getAttribute(phone);

//        获取Redis当中的短信验证码
        Object sessionIncode = redisTemplate.opsForValue().get(phone);
        log.info("Redis当中的验证码为："+sessionIncode);
//        输入的验证码比对session中的验证码 判断是否相同
        if (code.equals(sessionIncode)){
//            创建条件构造器
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

//        判断当前输入的手机号在数据库中是否存在，不存在则新建新用户
            User oneUser = userService.getOne(queryWrapper);
            if (oneUser==null){
                oneUser= new User();
                oneUser.setPhone(phone);
                oneUser.setStatus(1);
                oneUser.setAvatar("user.png");
                oneUser.setName(ValidateCodeUtils.generateValidateCode4String(6));
                userService.save(oneUser);
            }
            session.setAttribute("user",oneUser.getId());
//            完成登录删除当前用户的手机验证码
            redisTemplate.delete(phone);
//            返回数据，完成请求
            return R.success(oneUser);
        }
        return R.error("登录失败!请检查输入的信息是否有误");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出登录成功!");
    }
    @PostMapping("/getUserInfo")
    public R<User> getUserInfo(@RequestBody User user){
        log.info(user.toString());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(user.getPhone()!=null,User::getPhone,user.getPhone());

        User userOne = userService.getOne(lambdaQueryWrapper);
        return R.success(userOne);
    }
}
